import 'dart:math';

class Double {
  num value = 0;

  int offset = 1;

  Double(this.value) {
    offset = decimalDigit(value);
  }

  @override
  String toString() {
    return value.toString();
  }

  bool equals(dynamic other) {
    Double behind = typeConvert(other);
    return behind.value == value;
  }
}

extension DoubleCalculate on Double {
  Double operator -(dynamic other) {
    Double behind = typeConvert(other);
    int maxOffset = max(offset, behind.offset);
    double intResult = ((value * pow(10, maxOffset)).round() - (behind.value * pow(10, maxOffset)).round()) / pow(10, maxOffset);
    return Double(intResult);
  }

  Double operator +(dynamic other) {
    Double behind = typeConvert(other);
    int maxOffset = max(offset, behind.offset);
    double intResult = ((value * pow(10, maxOffset)).round() + (behind.value * pow(10, maxOffset)).round()) / pow(10, maxOffset);
    return Double(intResult);
  }

  Double operator *(dynamic other) {
    Double behind = typeConvert(other);
    double intResult = ((value * pow(10, offset)).round() * (behind.value * pow(10, behind.offset)).round()) / pow(10, offset + behind.offset);
    return Double(intResult);
  }

  Double operator /(dynamic other) {
    Double behind = typeConvert(other);
    double intResult = ((value * pow(10, offset)).round() / (behind.value * pow(10, behind.offset)).round()) / pow(10, offset - behind.offset);
    return Double(intResult);
  }
}

///类型转换
Double typeConvert(dynamic other) {
  if (other is num) {
    return Double(other);
  } else if (other is Double) {
    return other;
  } else if (other is String) {
    return Double(double.parse(other));
  } else {
    throw Exception('计算类型不支持！');
  }
}

/// 计算小数的位数
int decimalDigit(num n) {
  String nStr = n.toString();
  if (!nStr.contains('.')) {
    return 0;
  }
  List<String> list = nStr.split('.');
  String list1 = list[1];
  if (!list1.contains('e')) {
    return list1.length;
  }
  List<String> es = list1.split('e');
  return max(es[0].length - int.parse(es[1]), 0);
}
